package com.bbgwap.controller;

import com.alibaba.fastjson.JSON;
import com.bbgkh.model.BaseInfo;
import com.bbgkh.utils.UserUtils;
import com.bbgwap.model.WeChatInfo;
import com.bbgwap.utils.HttpUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import static com.bbgwap.base.APPCONST.BACK_URL;
import static com.bbgwap.base.APPCONST.WECHAT_INFO;

/**
 * Created by lixiang01 on 2/22/2017.
 */
@Controller
@CrossOrigin
public class WXController extends BaseController{

    private static final String appID= "wx9767d8078598c934";
    private static final String appSecret= "f317f6ca2ea23c1d4fffcfd75a2e5447";

    @GetMapping(value = "wx/getAccessCode")
    @ResponseBody
    public void getAccessCode(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String callBackUrl = "http://m.admin.bbgkh.shop/wx/getAccessCodeR";
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appID
                +"&redirect_uri="+ URLEncoder.encode(callBackUrl)
                +"&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
        logger.info("向微信第一次请求");
        response.sendRedirect(url);
    }

    @GetMapping(value = "wx/getAccessCodeR")
    @ResponseBody
    public String getAccessCodeR( HttpServletRequest request, HttpServletResponse response)  {
        BaseInfo baseInfo = new BaseInfo("0", "Come in Controller");
        String result ="";
        try {
            String wx_code = request.getParameter("code");
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appID + "&secret=" + appSecret + "&code=" + wx_code + "&grant_type=authorization_code";
            HttpRequestBase httpRequestBase = new HttpGet(url);
            CloseableHttpResponse http_response = null;
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                }
            };
            sslcontext.init(null, new TrustManager[]{tm}, null);
            HttpClient httpClient = HttpClientBuilder.create().setSslcontext(sslcontext).build();

            http_response = (CloseableHttpResponse) httpClient.execute(httpRequestBase);
            HttpEntity entity = http_response.getEntity();
            result = HttpUtils.entityToStr(entity);
            WeChatInfo weChatInfo = JSON.parseObject(result,WeChatInfo.class);
            request.getSession().setAttribute(WECHAT_INFO,weChatInfo);
            String backUrl  = (String) request.getSession().getAttribute(BACK_URL);
            logger.info("取出backUrl : "+backUrl);
            response.sendRedirect(backUrl);
        } catch (Exception e){
            e.printStackTrace();
        }finally {
            return JSON.toJSONString(baseInfo+result);
        }
    }
}
